$(function(){
	var types = {MENU:"菜单",FUNCTION:"功能",PAGE:"页面"};
	var grid = $('#systemRsource');
	//初始化表格
	grid.treegrid({
		fit:true,
		border:false,
	    url:'permission/resource/list',
	    idField:'id',
	    treeField:'text',
	    toolbar:"#systemRsourceToolbar",
	    columns:[[
	        {title:'名称',field:'text',width:180},
	        {field:'type',title:'类型',width:60,formatter:function(value,row,index){
	        		return types[value];
	        }},
	        {field:'identify',title:'标识',width:180},
	        {field:'enable',title:'状态',width:80,formatter:function(value,row,index){
	        		return value ? "可用":"禁用";
	        }}
	    ]]
	});
	
	// 为工具栏的按钮绑定事件
	$("#systemRsourceToolbar").on("click","a.add",function(){
		var dialog = $("<div/>").dialog({
			title: "新增资源",
			width: 450,
			height: 530,
			modal:true,
			href:'permission/resource/form',
			onClose: function(){
				//关闭窗户后，立即销毁窗口
				$(this).dialog("destroy");
			},
			buttons:[
				{
					iconCls:"icon-ok",
					text:"保存",
					handler:function(){
						var form = $("#systemRsourceForm");
						//校验表单数据
						if(form.form("validate")){
							$.post("permission/resource/save",form.serialize(),function(rs){
								if(rs.err){
									alert(rs.err);
								}else{
									//关闭当前窗口
									dialog.dialog("close");
									grid.treegrid("reload");
								}
							});
						}
					}
				},
				{
					iconCls:"icon-cancel",
					text:"取消",
					handler:function(){
						//关闭当前窗口
						dialog.dialog("close");
					}
				}
			]
		});
	}).on("click","a.edit",function(){
		var row = grid.treegrid("getSelected");
		if(row){
			var dialog = $("<div/>").dialog({
				title: "编辑资源",
				width: 450,
				height: 530,
				modal:true,
				href:'permission/resource/form/'+row.id,
				onClose: function(){
					//关闭窗户后，立即销毁窗口
					$(this).dialog("destroy");
				},
				buttons:[
					{
						iconCls:"icon-ok",
						text:"保存",
						handler:function(){
							var form = $("#systemRsourceForm");
							//校验表单数据
							if(form.form("validate")){
								$.post("permission/resource/save",form.serialize(),function(rs){
									if(rs.err){
										alert(rs.err);
									}else{
										//关闭当前窗口
										dialog.dialog("close");
										grid.treegrid("reload");
									}
								});
							}
						}
					},
					{
						iconCls:"icon-cancel",
						text:"取消",
						handler:function(){
							dialog.dialog("close");
						}
					}
				]
			});
		}
	}).on("click","a.delete",function(){
		var row = grid.treegrid("getSelected");
		if(row && (!row.children || row.children.length==0)){
			$.messager.confirm('删除提示', '确认删除此记录?', function(r){
                if (r){
                    $.get("permission/resource/delete/"+row.id,function(){
                    		grid.treegrid("reload");
                    }).error(function(){
                    		$.messager.alert("提示","删除失败,请先解除权限对应的所有角色关联!");
                    });
                }
            });
		}
	});
});